using System;
using System.Linq;
using DNT.RavenQA.Core.Extensions;
using DNT.RavenQA.Core.Models;
using Raven.Client;

namespace DNT.RavenQA.Web.Infrastructure.Commands
{
    public class SetQuestionAsViewedCommand : RavenCommand<SetQuestionAsViewedCommand.Input, VoidResult>
    {
        public struct Input
        {
            public Int32 QuestionId;
            public User User;
        }

        public SetQuestionAsViewedCommand(Input parameter)
            : base(parameter)
        {
        }

        public override VoidResult Execute(IDocumentSession session)
        {
            if (Parameter.User.IsNull())
                return VoidResult.Instance;

            ContributeViews views;

            var question = session.Include<Question>(x => x.ViewsId)
                .Load<Question>(Parameter.QuestionId);

            if (question.IsNull())
                throw new NonExistingContributeException();

            views = session.Query<ContributeViews>()
                .SingleOrDefault(x => x.QuestionId == question.Id);

            question.SetAsViewed(() =>
                                     {
                                         if (views.IsNull())
                                         {
                                             views = ContributeViews.New(question);
                                             session.Store(views);
                                         }

                                         return views;
                                     }, Parameter.User);

            return VoidResult.Instance;
        }
    }
}